import React, { useState, useRef } from 'react'
import { X, Upload } from 'lucide-react'

interface SettingsModalProps {
  onClose: () => void
  onBackgroundChange: (background: string) => void
  onSearchEngineChange: (searchEngine: string) => void
  onTitleChange: (title: string) => void
  currentBackground: string
  currentSearchEngine: string
  currentTitle: string
}

const predefinedBackgrounds = [
  'https://source.unsplash.com/random/1920x1080/?nature',
  'https://source.unsplash.com/random/1920x1080/?city',
  'https://source.unsplash.com/random/1920x1080/?abstract',
  'https://source.unsplash.com/random/1920x1080/?space',
]

const SettingsModal: React.FC<SettingsModalProps> = ({
  onClose,
  onBackgroundChange,
  onSearchEngineChange,
  onTitleChange,
  currentBackground,
  currentSearchEngine,
  currentTitle,
}) => {
  const [newBackground, setNewBackground] = useState(currentBackground)
  const [newSearchEngine, setNewSearchEngine] = useState(currentSearchEngine)
  const [newTitle, setNewTitle] = useState(currentTitle)
  const [customBackgroundUrl, setCustomBackgroundUrl] = useState('')
  const fileInputRef = useRef<HTMLInputElement>(null)

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    onBackgroundChange(newBackground)
    onSearchEngineChange(newSearchEngine)
    onTitleChange(newTitle)
    onClose()
  }

  const handleBackgroundChange = (background: string) => {
    setNewBackground(background)
    setCustomBackgroundUrl('')
  }

  const handleCustomBackgroundChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setCustomBackgroundUrl(e.target.value)
    setNewBackground(e.target.value)
  }

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      const reader = new FileReader()
      reader.onload = (event) => {
        if (event.target?.result) {
          setNewBackground(event.target.result as string)
          setCustomBackgroundUrl('')
        }
      }
      reader.readAsDataURL(file)
    }
  }

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center">
      <div className="bg-white rounded-lg p-8 w-96 max-h-[90vh] overflow-y-auto">
        <div className="flex justify-between items-center mb-4">
          <h2 className="text-2xl font-bold">Settings</h2>
          <button onClick={onClose} className="text-gray-500 hover:text-gray-700">
            <X size={24} />
          </button>
        </div>
        <form onSubmit={handleSubmit}>
          <div className="mb-4">
            <label htmlFor="title" className="block text-sm font-medium text-gray-700 mb-2">
              Page Title
            </label>
            <input
              type="text"
              id="title"
              value={newTitle}
              onChange={(e) => setNewTitle(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="Enter page title"
            />
          </div>
          <div className="mb-4">
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Background Image
            </label>
            <div className="grid grid-cols-2 gap-2 mb-2">
              {predefinedBackgrounds.map((bg, index) => (
                <button
                  key={index}
                  type="button"
                  onClick={() => handleBackgroundChange(bg)}
                  className={`h-20 bg-cover bg-center rounded-md border-2 ${
                    newBackground === bg ? 'border-blue-500' : 'border-transparent'
                  }`}
                  style={{ backgroundImage: `url(${bg})` }}
                />
              ))}
            </div>
            <input
              type="text"
              value={customBackgroundUrl}
              onChange={handleCustomBackgroundChange}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 mb-2"
              placeholder="Enter custom image URL"
            />
            <div className="flex items-center justify-between">
              <input
                type="file"
                ref={fileInputRef}
                onChange={handleFileChange}
                accept="image/*"
                className="hidden"
              />
              <button
                type="button"
                onClick={() => fileInputRef.current?.click()}
                className="flex items-center justify-center px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <Upload size={16} className="mr-2" />
                Upload Local Image
              </button>
              {newBackground.startsWith('data:image') && (
                <span className="text-sm text-green-600">Local image selected</span>
              )}
            </div>
          </div>
          <div className="mb-4">
            <label htmlFor="searchEngine" className="block text-sm font-medium text-gray-700 mb-2">
              Search Engine
            </label>
            <select
              id="searchEngine"
              value={newSearchEngine}
              onChange={(e) => setNewSearchEngine(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="google">Google</option>
              <option value="bing">Bing</option>
              <option value="duckduckgo">DuckDuckGo</option>
            </select>
          </div>
          <button
            type="submit"
            className="w-full bg-blue-500 text-white py-2 px-4 rounded-md hover:bg-blue-600 transition-colors"
          >
            Save Changes
          </button>
        </form>
      </div>
    </div>
  )
}

export default SettingsModal